package com.sdry.product.prehangingline.service;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.Query;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.sdry.basic.entity.Container;
import com.sdry.basic.entity.ContainerStare;
import com.sdry.basic.entity.Material;
import com.sdry.common.BaseAPIMessageTypeEnum;
import com.sdry.exception.BizException;
import com.sdry.exception.CommonEnum;
import com.sdry.good.goodWarehouse.mapper.GoodSortFrameMapper;
import com.sdry.product.prehangingline.entity.PreHangingLine;
import com.sdry.product.prehangingline.mapper.PreHangingLineMapper;
import com.sdry.product.prod.entity.LacquerInto;
import com.sdry.product.prod.entity.ProductHandleOut;
import com.sdry.product.prod.entity.ResultAppList;
import com.sdry.product.prod.mapper.LacquerIntoMapper;
import com.sdry.product.prod.mapper.ProductHandleOutMapper;
import com.sdry.product.prod.service.ProductHandleOutService;
import com.sdry.product.sorting.entity.SortFrame;
import com.sdry.product.sorting.mapper.SortReceivingDetailMapper;
import com.sdry.product.sorting.mapper.SortingStockMapper;
import com.sdry.untils.CustomUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @Description 预挂线app端
 * @Author chenBin
 * @Date 2020-04-23 10:54
 * @Version 1.0
 **/
@Service
@Transactional(rollbackFor = Exception.class)
public class PreOneLineAppServiceImpl implements PreOneLineAppService{

    @Resource
    private PreHangingLineMapper preHangingLineMapper;

    @Resource
    private LacquerIntoMapper lacquerIntoDao;

    @Resource
    private SortReceivingDetailMapper sortReceivingDetailMapper;

    @Resource
    private ProductHandleOutMapper productHandleOutMapper;

    @Resource
    private SortingStockMapper sortingStockMapper;

    @Override
    public void addPreOneLine(String json, String userId) {
        Gson gson = new Gson();
        ResultAppList<Material> materialResultAppList = gson.fromJson(json, ResultAppList.class);
        String jsonObject = String.valueOf(materialResultAppList.getList());
        List<Material> materialList= gson.fromJson(jsonObject, new TypeToken<List<Material>>() {}.getType());
        for (Material material : materialList) {
            PreHangingLine preHangingLine = new PreHangingLine();
            //挂架ID
            preHangingLine.setPylonsId(Long.parseLong(material.getPyId()));
            //工位编号
            preHangingLine.setStationNumber(materialResultAppList.getPsnumber());
            //必须是预挂线工位
            String remark = "YG";
            Long containerId = preHangingLineMapper.queryContainerByNumber(materialResultAppList.getPsnumber(),remark);
            if (containerId == null) {
                throw new BizException(BaseAPIMessageTypeEnum.A098.getName());
            }
            //工位
            preHangingLine.setStationId(containerId);
            //产品ID
            preHangingLine.setMaterielId(material.getMaId());
            //产品数量
            preHangingLine.setQuantity(material.getQuantity());
            //喷涂要求
            preHangingLine.setMaSprayingRequirements(material.getMaSprayingRequirements());
            //来源
            preHangingLine.setSource(material.getRemark04());

            preHangingLine.setCreateBy(userId);
            //紧急程度
            preHangingLine.setRemark(materialResultAppList.getUrgency());
            QueryWrapper<PreHangingLine> queryWrapper05 = new QueryWrapper<>();
            queryWrapper05.eq("status",0L).eq("materiel_id",material.getMaId())
                    .eq("station_id",containerId);
            //判断库存是否有，如果有增加数量，没有新增
            /*List<PreHangingLine> preHangingLines = preHangingLineMapper.selectList(queryWrapper05);
            if (preHangingLines.size() > 0) {
                PreHangingLine preHangingLine02 = new PreHangingLine();
                //原来的数量加上现在的数量
                Long quantity = preHangingLines.get(0).getQuantity() + material.getQuantity();
                preHangingLine02.setQuantity(quantity);
                preHangingLineMapper.update(preHangingLine02,queryWrapper05);
            }else {

            }*/
            preHangingLineMapper.insert(preHangingLine);

            /**
             * 预挂线绑定时：分拣区或者前处理区的物料，
             * 绑定数量和库存数量
             * 1.绑定数量大于库存数量
             * 2.绑定数量等于库存数量，更改GoSourceId 为值
             * 3.绑定数量小于库存数量，
             */
            //绑定数量
            Long quantity = material.getQuantity();

            if (material.getRemark04().equals("QCL")){
                //库存数量
                Long stockQuantity = 0L;
                QueryWrapper<ProductHandleOut> queryWrapper02 = new QueryWrapper<>();
                //查询条件
                queryWrapper02.eq("status",2L)
                        .eq("station_id",material.getPsId())
                        .eq("materials_id",material.getMaId());
                List<ProductHandleOut> productHandleOutList = productHandleOutMapper.selectList(queryWrapper02);
                for (ProductHandleOut productHandleOut : productHandleOutList) {
                    stockQuantity += productHandleOut.getQuantity();
                }

                //一个工位显示多行的时候
                for (ProductHandleOut productHandleOut : productHandleOutList) {
                    //物料数量
                    Long maQuantity = productHandleOut.getQuantity();
                    //绑定数量等于库存数量，更改GoSourceId 为值
                    if (quantity.equals(stockQuantity)){
                        ProductHandleOut productHandleOut01 = new ProductHandleOut();
                        //来源的工位ID
                        productHandleOut01.setGoSourceId(containerId.toString());
                        productHandleOutMapper.update(productHandleOut01,queryWrapper02);
                    }else if (quantity > stockQuantity){
                        //绑定数量大于库存数量
                        throw new BizException(BaseAPIMessageTypeEnum.A096.getName());
                    }else if (quantity < stockQuantity){
                        //绑定数量小于库存数量,1.绑定数量大于单个物料数量2.绑定数量小于等于单个数量
                        ProductHandleOut productHandleOut02 = new ProductHandleOut();
                        Long newQuantity = 0L;
                        if (quantity > maQuantity){
                            newQuantity = quantity - maQuantity;
                            quantity = newQuantity;
                            productHandleOut02.setQuantity(newQuantity);
                        }else if (quantity < maQuantity){
                            newQuantity = maQuantity - quantity;
                            productHandleOut02.setQuantity(newQuantity);
                        }else if (quantity.equals(maQuantity)){
                            //来源的工位ID
                            productHandleOut02.setGoSourceId(containerId.toString());
                        }
                        productHandleOutMapper.update(productHandleOut02,queryWrapper02);
                    }
                }
            }else if (material.getRemark04().equals("FJ")){
                //更改分拣区状态来源ID
                QueryWrapper<SortFrame> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("status",2L)
                        .eq("container_id",material.getPsId());
                //库存查询
                String status = "2";
                ContainerStare containerStare = sortingStockMapper.queryContainerStare(material.getPsId(),material.getMaId(),status);
                Long stockQuantity = Long.valueOf(containerStare.getCsrnum());
                //绑定数量等于库存数量，更改GoSourceId 为值
                if (quantity.equals(stockQuantity)){
                    SortFrame sortFrame = new SortFrame();
                    //来源的工位ID
                    sortFrame.setSource(containerId.toString());
                    int update = sortingStockMapper.update(sortFrame, queryWrapper);
                    if(update <= 0){
                        throw new BizException(BaseAPIMessageTypeEnum.A095.getName());
                    }
                    //删除装载表信息
                    sortReceivingDetailMapper.deleteContainerStareQuantity2(Long.parseLong(material.getPsId()));
                }else if (quantity > stockQuantity){
                    //绑定数量大于库存数量
                    throw new BizException(BaseAPIMessageTypeEnum.A096.getName());
                }else if (quantity < stockQuantity){
                    //绑定数量小于库存数量
                    Long newQuantity = stockQuantity - quantity;
                    Integer effect = sortReceivingDetailMapper.updateContainerStareQuantity3(material.getPsId(), material.getMaId(), newQuantity, userId);
                    if(effect <= 0){
                        throw new BizException(BaseAPIMessageTypeEnum.A095.getName());
                    }
                }
            }
        }
    }

    @Override
    public List<ResultAppList<Material>> queryRegionMateriel(String regionType) {
        List<ResultAppList<Material>> resultAppListList = preHangingLineMapper.queryRegionMateriel();
        return resultAppListList;
    }

    @Override
    public List<ResultAppList<Material>> queryRegionPreHangingLineMateriel(String permissionType) {
        List<Material> materialList= preHangingLineMapper.queryRegionPreHangingLineMateriel(permissionType);
        return CustomUtil.QueryResultChange(materialList);
    }

    @Override
    public List<ResultAppList<Material>> queryPreOneLineMateriel(String psNumber) {
        List<ResultAppList<Material>> newResultAppListList = new ArrayList<>();
        String[] containerNumbers = psNumber.split(",");
        Set<String> HashSet = new HashSet<String>();
        List<Material> materials =  preHangingLineMapper.queryPreOneLineMateriel(containerNumbers);
        List<ResultAppList<Material>> resultAppListList = CustomUtil.QueryResultChange(materials);
        //去除已经入倒喷涂线的
        /*for (String containerNumber : containerNumbers) {
            QueryWrapper<LacquerInto> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("status",0L).eq("remark",containerNumber);
            List<LacquerInto> lacquerIntos = lacquerIntoDao.selectList(queryWrapper);
            if (lacquerIntos.size() > 0) {
                HashSet.add(containerNumber);
            }
        }
        for (ResultAppList<Material> materialResultAppList : resultAppListList) {
            if (!HashSet.contains(materialResultAppList.getPsnumber())){
                newResultAppListList.add(materialResultAppList);
            }
        }*/
        return resultAppListList;
    }

    @Override
    public List<ResultAppList<Material>> queryTransitreaMateriel() {
        List<Material> materialList= preHangingLineMapper.queryTransitreaMateriel();
        return CustomUtil.QueryResultChange(materialList);
    }
}
